package com.hsnr.findyourbuddy;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    Button map, contacts, options, register;
    static String ip = null;
    static int port = 999;
    public String phonenumber, serverport, serverip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (!isNetworkAvailable()) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setMessage("Datenverbindung ist deaktiviert. Bitte aktivieren Sie zuerst Ihre mobile Datenverbindung und starten Sie diese App erneut!");
            builder.setCancelable(false);
            builder.setTitle("Fehler!");
            builder.setPositiveButton("OK", new OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    MainActivity.this.finish();

                }
            });
            builder.show();

        }

        map = (Button) findViewById(R.id.map);
        contacts = (Button) findViewById(R.id.contacts);
        options = (Button) findViewById(R.id.options);

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        boolean firstRun = sharedPrefs.getBoolean("firstRun", true);
        if (firstRun) {
            Editor editor = sharedPrefs.edit();
            editor.putBoolean("firstRun", false);
            editor.commit();
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            startActivity(intent);
        }
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        ip = sharedPrefs.getString("prefIp", "85.214.231.200");
        port = Integer.parseInt(sharedPrefs.getString("prefPort", "999"));

        Intent service = new Intent(this, UpdateService.class);
        this.startService(service);
    }

    private void synchronizeContacts() {
        final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this,
                Messages.getString("MainActivity.11"), //$NON-NLS-1$
                Messages.getString("MainActivity.12"), true); //$NON-NLS-1$
        ringProgressDialog.setCancelable(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread t = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            boolean errorOccured = false;
                            CommunicationHandler ch = null;
                            try {
                                ch = new CommunicationHandler(ip, port);
                            } catch (IOException e2) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ringProgressDialog.dismiss();

                                        Toast.makeText(getApplicationContext(),
                                                Messages.getString("MainActivity.13"), Toast.LENGTH_LONG).show(); //$NON-NLS-1$
                                    }
                                });
                                e2.printStackTrace();
                            }
                            if (ch != null) {
                                try {
                                    ch.sendContactRequest(getApplicationContext());

                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                    errorOccured = true;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            ringProgressDialog.dismiss();

                                            Toast.makeText(getApplicationContext(),
                                                    Messages.getString("MainActivity.14"), Toast.LENGTH_LONG) //$NON-NLS-1$
                                                    .show();
                                        }
                                    });
                                }
                                if (!errorOccured) {
                                    try {
                                        final ContactResponse cres = (ContactResponse) ch
                                                .receiveResponse(ContactResponse.class);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (cres.isSuccess()) {
                                                    ringProgressDialog.dismiss();
                                                    Toast.makeText(getApplicationContext(),
                                                            Messages.getString("MainActivity.15"), Toast.LENGTH_LONG).show(); //$NON-NLS-1$
                                                } else {
                                                    ringProgressDialog.dismiss();
                                                    Toast.makeText(getApplicationContext(),
                                                            Messages.getString("MainActivity.16"), Toast.LENGTH_LONG).show(); //$NON-NLS-1$
                                                }
                                            }
                                        });
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                        errorOccured = true;
                                        runOnUiThread(new Runnable() {

                                            @Override
                                            public void run() {
                                                ringProgressDialog.dismiss();
                                                Toast.makeText(getApplicationContext(),
                                                        Messages.getString("MainActivity.17"), Toast.LENGTH_LONG) //$NON-NLS-1$
                                                        .show();
                                            }
                                        });
                                    } catch (SystemException ex) {
                                        ex.printStackTrace();
                                        final String e = ex.getMessage();
                                        errorOccured = true;
                                        runOnUiThread(new Runnable() {

                                            @Override
                                            public void run() {
                                                ringProgressDialog.dismiss();
                                                Toast.makeText(getApplicationContext(), Messages.getString(e),
                                                        Toast.LENGTH_LONG) //$NON-NLS-1$
                                                        .show();
                                            }
                                        });
                                    }
                                }
                            }
                            if (ch != null) {
                                ch.close();
                            }
                        }
                    });
                    t.start();
                    t.join();
                } catch (Exception e) {
                    ringProgressDialog.dismiss();
                }
            }
        }).start();

    }

    public void onClick(View v) {
        if (v.getId() == R.id.map) {
            Intent intent = new Intent(MainActivity.this, MapActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.contacts) {
            synchronizeContacts();
        } else if (v.getId() == R.id.options) {
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            startActivity(intent);
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnected();
    }

}
